<template>
	<view class="content" :style="{ height: windowHeight + 'px' }">
		<view class="header" v-if="timer">
			<!-- <image class="touxiang" :src="avatarImage" alt=""></image> -->
			<view class="touxiang">
				匹配中
			</view>
			<view class="pipei">
				正在匹配
			</view>
		</view>
		<view class="center" v-if="timer">
			<view class="title">
				匹配倒计时
			</view>
			<view class="times">
				{{ waitingTime }}
			</view>
		</view>
		<!-- 对手信息 -->
		<view class="tops" v-if="!timer">
			<image class="touxiang" :src="res2.avatarImage" alt=""></image>
			<view class="bottom_left">
				<view class="bottom_left_one">
					<text>{{ res2.opponentNetName }}</text>
				</view>
				<view class="bottom_left_two">
					已玩 {{ res2.opponentFinishedNum }} 次，胜率： {{ res2.opponentWinRate }}
				</view>
			</view>
		</view>
		<!-- 抢题==>答题 -->
		<view class="contents" v-if="!timer && !bottomShow && list.length > 0"
			:style="{ backgroundColor: disabledButton ? 'rgb(11,151,204)' : 'rgba(78, 191, 245)' }">
			<view class="label">
				第{{ step }}题
			</view>
			<view class="names">
				{{ list[step - 1].name }}
			</view>
			<view class="value">
				<view class="div_view" v-for="(item, index) in list[step - 1].answer" :key="index"
					@click="radioClick(optionList[index], list[step - 1].max, list[step - 1].type)"
					:style="{ backgroundColor: conputedColor(optionList[index]) }">
					<view class="value_option">
						{{ optionList[index] }}
					</view>
					<view class="titles">
						{{ item }}
					</view>
				</view>
			</view>
		</view>

		<view class="buttons" @click="submit" v-if="!timer && !bottomShow" :style="{ backgroundColor: disabledButton ? 'rgb(11,151,204)' : 'rgba(254, 0, 0)' }">
			{{ disabledButtonText + answerTimer }}
		</view>

		<view class="bottom_show" v-if="bottomShow" :style="{ backgroundColor: conputedsColor() }">
			<view v-if="loading" class="upLoad_loading loading">
				<u-loading-icon color="#fff"></u-loading-icon>
			</view>
			<view v-else class="answers">
				<view class="answers_title">{{ isWin == 1 ? '成功胜利' : isWin == 2 ? '失败了' : '平手' }}</view>
				<view class="answers_mes">{{ isWin == 1 ? '恭喜啦' : isWin == 2 ? '下次加油' : '实力对等，再来一次' }}</view>
				<view class="answers_imgs">
					<image class="touxiang" :src="res2.avatarImage" alt="" v-if="isWin != 1 && isWin != 2"></image>
					<image class="touxiangs" v-if="isWin != 1 && isWin != 2"
						src="https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/24/1753350514137.png?x-oss-process=image/resize,w_300"
						alt=""></image>
					<image class="touxiang" :src="avatarImage" alt=""></image>
				</view>
			</view>
		</view>

		<view class="bottom_buttons" v-if="bottomShow && !loading">
			<view class="cancel" @click="cnacel">退出</view>
			<view class="onces" @click="onces">再来一次</view>
		</view>

		<view class="bottom">
			<view class="bottom_left">
				<view class="bottom_left_one">
					<text>{{ response.nickName }}</text>
				</view>
				<view class="bottom_left_two">
					已玩 {{ response.myFinishedNum }} 次，胜率： {{ response.myWinRate }}
				</view>
			</view>
			<image class="touxiang" :src="avatarImage" alt=""></image>
		</view>
	</view>
</template>

<script>
	import {
		getInfo,
		listPk,
		winRate,
		pollingRandomMatch,
		robQuestion,
		submitAnswer,
		getPkInfo,
		getResult
	} from '@/api/index.js'
	import config from '@/config/config.js'
	import {
		systemInfo
	} from '../../utils/mixin'
	export default {
		components: {},
		mixins: [systemInfo],
		data() {
			return {
				avatarImage: '',
				waitingTime: 10, // 等待时间
				answerTime: 60, // 答题时间
				timer: null, // 计时器
				response: {}, // 个人信息

				list: [],
				optionList: [
					'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'
				],
				step: 1,
				total: 0,
				// 作答答案
				answerList: [],

				answerTimer: 0, // 答题倒计时
				answerTimerId: null, // 答题计时器ID

				loading: false, // pk结果等待时间
				bottomShow: false, // pk结果

				disabledButton: false, // 禁用按钮不可点击
				disabledButtonText: '开始抢题', // 禁用后按钮展示文字

				// 对手信息
				res2: {},
				// pk结果
				isWin: '',

			}
		},
		onLoad() {
			// 状态栏高度
			this.getSystemInfo();
			this.getDetail();
			this.getlistPk();
		},
		methods: {
			// 获取详细信息
			async getDetail() {
				const res = await getInfo()
				this.avatarImage = res.data.user.avatarImage ? (config.pic_prefix + res.data.user.avatarImage) :
					'https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/1/1751337747449.png'

				const res1 = await winRate()
				this.response = res1.data
				this.response.nickName = res.data.user.netName
			},
			// 获取匹配机制
			async getlistPk() {
				const res = await listPk({
					pageNum: 1,
					pageSize: 10
				})
				this.waitingTime = res.rows[0].waitingTime
				this.answerTime = res.rows[0].answerTime

				this.startCountdown()
			},
			// 匹配倒计时
			startCountdown() {
				this.timer = setInterval(async () => {
					if (this.waitingTime > 0) {
						this.waitingTime--;
						// 轮询查询是否匹配到用户
						const res = await pollingRandomMatch()
						if (res.data.rows.length > 0) {
							// 获取对手头像等信息
							const res2 = await getPkInfo({
								codeId: res.data.rows[0].codeId
							})
							res2.data.avatarImage = res2.data.opponentAvatarImage ? (config.pic_prefix + res2
									.data.opponentAvatarImage) :
								'https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/1/1751337747449.png'
							this.res2 = res2.data

							// 按照 id 倒序排列
							res.data.rows.sort((a, b) => b.id - a.id);
							res.data.rows.forEach((item) => {
								item.value = item.id
								if (item.type == '单选' || item.type == '多选') {
									item.answer = [item.optionA, item.optionB, item.optionC, item
										.optionD
									]
									if (item.type == '单选') {
										item.max = 1
									}
									if (item.type == '多选') {
										item.max = 4
									}
								} else if (item.type == '判断') {
									item.answer = ['正确', '错误']
									item.max = 1
								}
							})

							this.list = res.data.rows
							this.answerList = new Array(res.data.total).fill([])
							this.total = res.data.total

							clearInterval(this.timer);
							this.timer = null;

							// 按钮可抢题
							this.disabledButton = false
							// 按钮文字重置
							this.disabledButtonText = '开始抢题'
							// 开始答题倒计时
							this.startAnswerCountdown();
						}
					} else {
						clearInterval(this.timer);
						this.timer = null;
						// uni.$u.toast("超时匹配 请重新匹配")
						uni.showModal({
							title: '是否重新匹配',
							success: (res) => {
								if (res.confirm) {
									this.getlistPk()
								} else if (res.cancel) {
									uni.switchTab({
										url: '/pages/tabbar/mine/mine'
									})
								}
							}
						})
					}
				}, 1000);
			},

			conputedColor(item) {
				return this.answerList[this.step - 1].includes(item) ? 'rgba(233,241,244,0.5)' : ''
			},
			conputedsColor() {
				// 赢
				if (this.isWin == 1) {
					return 'rgb(254,0,0)'
				} else if (this.isWin == 2) { // 输
					return 'rgb(2,104,144)'
				} else {
					return 'rgb(11,151,204)'
				}
			},
			// 单选事件
			radioClick(item, max, type) {
				// 抢题后不可点击选中选项
				if (!this.disabledButton) {
					// 再次点击取消
					if (this.answerList[this.step - 1].includes(item)) {
						const list = JSON.parse(JSON.stringify(this.answerList[this.step - 1]))
						const indexs = list.indexOf(item)
						list.splice(indexs, 1)
						this.answerList.splice(this.step - 1, 1, list)
					} else {
						// 选择的最大阈值
						if (this.answerList[this.step - 1].length < max) {
							const list = JSON.parse(JSON.stringify(this.answerList[this.step - 1]))
							list.push(item)
							this.answerList.splice(this.step - 1, 1, list)
						}
					}
				}
			},
			// 下一题
			async submit() {
				// 禁用按钮不可抢题
				if (!this.disabledButton) {
					if (this.answerList[this.step - 1].length > 0) {
						const res = await robQuestion({
							questionId: this.list[this.step - 1].id,
							codeId: this.list[this.step - 1].codeId
						})
						// 抢题成功
						if (res.data && res.code == 200) {
							// 按钮文字重置
							this.disabledButtonText = '抢题成功'
						} else {
							// 按钮文字重置
							this.disabledButtonText = '抢题失败'
							// 抢题失败 答案置空
							this.answerList.splice(this.step - 1, 1, [])
						}
						if (res.code == 200) {
							// 禁用按钮不可抢题
							this.disabledButton = true
						}
					} else {
						uni.$u.toast('请选择答案');
					}
				}
			},


			// 开始答题倒计时
			startAnswerCountdown() {
				// 先清除已存在的计时器
				if (this.answerTimerId) {
					clearInterval(this.answerTimerId);
					this.answerTimerId = null;
				}

				this.answerTimer = this.answerTime;
				// this.answerTimer = 5;
				this.answerTimerId = setInterval(() => {
					if (this.answerTimer > 0) {
						this.answerTimer--;
					} else {
						// 按钮可抢题
						this.disabledButton = false
						// 按钮文字重置
						this.disabledButtonText = '开始抢题'
						// 倒计时结束，自动跳到下一题
						this.autoSubmit();
					}
				}, 1000);
			},
			// 自动提交（倒计时结束时调用）
			async autoSubmit() {
				// 清除计时器
				if (this.answerTimerId) {
					clearInterval(this.answerTimerId);
					this.answerTimerId = null;
				}

				// 如果不是最后一题
				if (this.step != this.total) {

					// 进入下一题
					this.step = this.step + 1

					// 重新开始倒计时
					this.startAnswerCountdown();
				} else {
					// 如果是最后一题，可以在这里处理结束逻辑
					const list = []
					this.answerList.forEach((item, index) => {
						list.push({
							codeId: this.list[index].codeId,
							questionId: this.list[index].id,
							userAnswer: this.list[index].type == '判断' ? (item.join(',') == 'A' ? '正确' :
								'错误') : this.list[index].type == '简答' ? item : item.join(',')
						})
					})
					this.bottomShow = true
					this.loading = true
					// 提交答案
					await submitAnswer(list)
					setTimeout(async () => {
						const res = await getResult({
							codeId: this.list[0].codeId
						})
						this.isWin = res.data.isWin
						this.loading = false
					}, 2000)
				}
			},

			// 退出
			cnacel() {
				uni.switchTab({
					url: '/pages/tabbar/mine/mine'
				})
			},
			// 再来一次
			onces() {
				this.loading = true
				setTimeout(() => {
					this.bottomShow = false
					this.list = []
					this.answerList = []
					this.step = 1
					this.total = 0
					this.getlistPk()
					this.loading = false
				}, 3000)
			}
		}
	}
</script>

<style lang="less" scoped>
	.content {
		width: 100%;
		box-sizing: border-box;
		padding: 80px 20px;
		background-color: rgba(34, 175, 229);
		position: relative;

		.header {
			display: flex;
			align-items: center;
			width: 100%;

			.touxiang {
				width: 90rpx;
				height: 90rpx;
				border-radius: 50%;
				margin-right: 10px;
				text-align: center;
				line-height: 90rpx;
				background-color: #fff;
				color: rgba(179, 173, 173, 0.5);
				font-size: 20rpx;
			}

			.pipei {
				color: #fff;
				font-size: 40rpx;
			}
		}

		.buttons {
			width: 200rpx;
			height: 60rpx;
			text-align: center;
			line-height: 60rpx;
			color: #fff;
			background-color: rgba(254, 0, 0);
			border-radius: 10rpx;
			margin-top: 40rpx;
			margin-left: 50%;
			transform: translateX(-50%);
		}

		.bottom_buttons {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 40rpx;

			.cancel {
				width: 200rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				margin-left: 20rpx;
				border-radius: 10rpx;
				color: #fff;
				background-color: rgba(2, 104, 144);
			}

			.onces {
				width: 200rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				margin-left: 20rpx;
				border-radius: 10rpx;
				color: #fff;
				background-color: rgba(254, 0, 0);
			}
		}

		.bottom_show {
			height: 500rpx;
			box-sizing: border-box;
			overflow: auto;
			background-color: rgba(78, 191, 245);
			border-radius: 40rpx;
			color: #fff;
			margin-top: 200rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.answers {
				text-align: center;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				align-content: space-around;
				width: 100%;
				height: 100%;
				padding: 40rpx;
				box-sizing: border-box;

				.answers_title {
					font-size: 50rpx;
					width: 100%;
				}

				.answers_mes {
					font-size: 30rpx;
					width: 100%;
				}

				.answers_imgs {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 180rpx;
						height: 180rpx;
						border-radius: 50%;
					}

					.touxiangs {
						width: 60rpx;
						height: 60rpx;
						margin: 0 10rpx;
					}
				}
			}
		}

		.contents {
			box-sizing: border-box;
			padding: 0 40rpx;
			max-height: calc(100% - 400rpx);
			overflow: auto;
			background-color: rgba(78, 191, 245);
			border-radius: 40rpx;
			color: #fff;
			margin-top: 200rpx;

			.title {
				color: #03a9f4;
				margin-top: 80rpx;
				font-size: 30rpx;
			}

			.label {
				font-weight: 500;
				font-size: 36rpx;
				margin-top: 40rpx;
				margin-bottom: 40rpx;
				text-align: center;
			}

			/deep/.u-textarea {
				margin-top: 80rpx;
			}

			.value {
				display: flex;
				width: 100%;
				align-items: center;
				font-size: 36rpx;
				box-sizing: border-box;
				flex-wrap: wrap;
				margin-bottom: 40rpx;

				.value_option {
					margin-right: 40rpx;
					width: 34rpx;
					height: 34rpx;
					font-size: 32rpx;
					text-align: center;
					line-height: 34rpx;
					margin-left: 40rpx;
				}

				.titles {
					width: calc(100% - 34rpx);
				}

				.div_view {
					width: 100%;
					display: flex;
					align-items: center;
					min-height: 60rpx;
					margin-top: 40rpx;
					border-radius: 60rpx;
				}
			}



		}

		.center {
			width: 100%;
			margin-top: 50%;
			transform: translateY(-50%);
			color: #fff;
			font-size: 40rpx;

			.title {
				width: 100%;
				text-align: center;
			}

			.times {
				width: 100%;
				text-align: center;
				font-size: 60rpx;
			}
		}

		.tops {
			width: 100%;
			position: absolute;
			top: 80px;
			left: 20px;
			display: flex;
			align-items: center;
			justify-content: flex-start;

			.bottom_left {
				height: 90rpx;
				margin-right: 20rpx;

				.bottom_left_one {
					height: 45rpx;
					color: #fff;
					font-size: 40rpx;
					text-align: left;

					.zhiwei {
						font-size: 20rpx;
						margin-right: 20rpx;
					}
				}

				.bottom_left_two {
					height: 45rpx;
					font-size: 20rpx;
					color: rgba(255, 255, 255, 0.5);
					display: flex;
					align-items: flex-end;
				}
			}

			.touxiang {
				width: 90rpx;
				height: 90rpx;
				border-radius: 50%;
				margin-right: 10px;
			}
		}

		.bottom {
			width: 100%;
			position: absolute;
			bottom: 80px;
			right: 20px;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			.bottom_left {
				height: 90rpx;
				margin-right: 20rpx;

				.bottom_left_one {
					height: 45rpx;
					color: #fff;
					font-size: 40rpx;
					text-align: right;

					.zhiwei {
						font-size: 20rpx;
						margin-right: 20rpx;
					}
				}

				.bottom_left_two {
					height: 45rpx;
					font-size: 20rpx;
					color: rgba(255, 255, 255, 0.5);
					display: flex;
					align-items: flex-end;
				}
			}

			.touxiang {
				width: 90rpx;
				height: 90rpx;
				border-radius: 50%;
				margin-right: 10px;
			}
		}

	}

	.upLoad_loading {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading {
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
	}
</style>